package Reader

import (
	"bufio"
	"fmt"
	"io"
	"log_process/system"
	"os"
	"time"
)

type ForFileReader struct {
	Path string
}

func (read *ForFileReader) Read(readChan chan []byte) {

	var (
		file   *os.File
		err    error
		reader *bufio.Reader
		data   []byte
	)

	if file, err = os.Open(read.Path); err != nil {
		system.TypeMonitorChan <- system.TypeErrNum
		panic(fmt.Sprintf("Open error：%s", err.Error()))
	}

	defer file.Close()

	if _, err = file.Seek(0, 2); err != nil {
		system.TypeMonitorChan <- system.TypeErrNum
		panic(fmt.Sprintf("Seek error：%s", err.Error()))
	}

	reader = bufio.NewReader(file)
	for {

		data, err = reader.ReadBytes('\n')

		if err == io.EOF {
			time.Sleep(500 * time.Millisecond)
			continue
		} else if err != nil {
			system.TypeMonitorChan <- system.TypeErrNum
			panic(fmt.Sprintf("ReadBytes error：%s", err.Error()))
		}

		system.TypeMonitorChan <- system.TypeHandleLine
		readChan <- data[:len(data)-1]
	}
}
